/**
 * 封装 axios 请求模块
 */
//  import router from '../router/router';
 import axios from "axios"
import { tansParams, blobValidate } from "@/utils/ruoyi";
import { saveAs } from "file-saver";
 import { Notification, MessageBox, Message, Loading } from "element-ui";
 //http://192.168.0.198:8081/api/index/bhlist         
 const request  = axios.create({ 
  //  baseURL: "https://apply.hnzyxsbh.com" // 基础路径
   baseURL: "http://192.168.0.28:8082/" // 基础路径
 })
// const that=this
// // //3. 定义前置拦截器，请求拦截器，请求发送出去之前触发的
request.interceptors.request.use((config) => {
  // console.log("config",config);

  //config 接口请求的配置信息
  // config.headers.Authorization={
  // }
  // config.headers.token= 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiIwMDoxIiwicm5TdHIiOiJ6M3pWelRiODJjRW5rNG1TaEgwZEVmNUJjUVJpdFhsUyIsInVzZXJJZCI6MX0.Ds2QRQ43dko96f5x3vKn4Bcgi4QZlHfZ5yh2QDjqdY0'
  config.headers.Authorization='Bearer '+ sessionStorage.getItem("token")
  return config;
}, (error) => {
  console.log("config: " , error);

  //报错的是时候抛出一个报错的信息
  return Promise.reject(error.response.status);
})

//4. 定义后置拦截器,响应拦截器, 服务器响应回来数据之前触发，
request.interceptors.response.use((response) => {
// console.log("response:",response.status);

  //响应回来的数据操作
  return response;
}, (error) => {

  console.log(error);
  if(error.response.status =="401"){
// 命名的路由  params ，地址栏不会暴露（userId）
// router.push({name:'name',params:{index:401}})
//params获取

    // router.push({ path: '/name', query: { myId: 401 }})
    return
  }
  //报错的是时候抛出一个报错的信息
  // return Promise.reject(error);
})

// 通用下载方法
export function download(url, params, filename, config) {
 let downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return request
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params);
        },
      ],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
      ...config,
    })
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        Message.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      Message.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}

 export default request 